package ivraustral;
import java.io.File;
import java.io.IOException;
import java.io.SequenceInputStream;
import java.util.Vector;
import java.util.regex.Pattern;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.Line;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
import javax.sound.sampled.LineUnavailableException;


public class AudioHandler implements LineListener {
	
	private Clip clip;
	private boolean finished = false;
	
	public AudioHandler() throws Exception {
		Line.Info linfo = new Line.Info(Clip.class);
		Line line = AudioSystem.getLine(linfo);
		clip = (Clip) line;
		clip.addLineListener(this);
		

	}

	public AudioInputStream getStream(String name){

		try {
			AudioInputStream clip = AudioSystem.getAudioInputStream(new File("audio/" + name + ".wav"));
			return clip;
		} catch (Exception e) {
			e.printStackTrace();
		}	
		return null;

	}
	
	
	public boolean hasFinished(){
		return finished;
	}
	
	public void update(LineEvent le) {
		LineEvent.Type type = le.getType();
		if (type == LineEvent.Type.OPEN) {
		  System.out.println("OPEN");
		  clip.stop(); // Revisar si es necesario hacer stop antes de reabrir un canal
		} else if (type == LineEvent.Type.CLOSE) {
		  System.out.println("CLOSE");
		} else if (type == LineEvent.Type.START) {
		  System.out.println("START");
		} else if (type == LineEvent.Type.STOP) {
		  finished = true;
		  clip.stop();
		  System.out.println("STOP");
		}
	}
	
	public void reproduce(String[] audioNames) throws LineUnavailableException, IOException{
		
		
		Vector<AudioInputStream> streams = new Vector<AudioInputStream>();
		int frameLength = 0;
	    for (int i = 0; i < audioNames.length; i++) {
	      
	      if(audioNames[i].startsWith("+")){
	    	  for(int j=0; j<audioNames[i].length();j++){
	    		  AudioInputStream stream = getStream("+");
	    	      streams.addElement(stream);
	    	      frameLength += stream.getFrameLength();  
	    	  }
	      }else{
		      AudioInputStream stream = getStream(audioNames[i]);
		      streams.addElement(stream);
		      frameLength += stream.getFrameLength();
	      }
	    }

		AudioInputStream appendedFiles = 
				new AudioInputStream(
					new SequenceInputStream(streams.elements()),
					streams.get(0).getFormat(),
					frameLength);
		clip.open(appendedFiles);
		clip.start();	
		
		while (!hasFinished());
		
	}
	

}
